<?php


namespace frontend\controllers;
use Yii;
use frontend\models\User;
use frontend\models\Goods;
use frontend\models\Order;

class BuyController extends BaseController
{
    /*秒杀接口*/
    public function actionIndex(){
        $user_id=User::getUserId();

     $goods_id=Yii::$app->request->get('goods_id')?Yii::$app->request->get('goods_id'):18;
      $goods_price=Goods::getGoods($goods_id)->goods_price;
     //从redis队列取出数据
       $count=Yii::$app->redis->lpop('goods'.$goods_id);

     if($count==1){
         $customer = Goods::findOne($goods_id);
         $order=new Order();

         //$order=Order::findOne(10);
         $transaction = Yii::$app->db->beginTransaction();
         try {
             $order->order_time=time();
             $order->user_id=$user_id;
             $order->order_status=1;
             $order->order_address="北京海淀shangdiqijie";
             $order_price=$goods_price;
             $order->save();
             $customer->goods_num = $customer->goods_num-1;
             $customer->save();
             // ...other DB operations...
            // Order::addOrder($goods_id);
//             $order=new Order();
//             $order->order_address="上地七街";
//             $order->save();
             $transaction->commit();
         }catch(\Throwable $e) {
             $transaction->rollBack();
             throw $e;
         }
         echo "1";
         //echo json_encode("秒杀成功");
     }else
     {
         echo "0";
         //echo json_encode("该商品已被抢空");
     }
    }

}